<template>
  <el-container>
    <!-- <RegionTree style="margin-top: 16px" @on-choose-region="filetrRegion" /> -->
    <el-main>
      <div class="default-main ba-table-box">
        <TableHeader
          :buttons="['refresh', 'comSearch']"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" @action="baTable.onTableAction" />
      </div>
    </el-main>
  </el-container>
</template>
<script setup lang="ts">
import {
  ref,
  provide,
  onMounted,
  markRaw,
  onBeforeUnmount,
  reactive,
  inject,
} from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import { DeviceMAccess } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { useAccess } from "@/store/backend/DeviceM/access";
import { useBusiness } from "@/store/backend/BusinessM/info";
import { useRouter, useRoute, onBeforeRouteUpdate } from "vue-router";
import { useRegion } from "@/store/backend/SysM/region";
import { useBackendMonitor } from "@/store/backend/EquipM/monitor"; //实时设备监控仓库
import _ from "lodash";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { useDictionary } from "@/store/backend/tool/dictionary";
import { getDictData } from "@/utils/common";
import { useCarbon } from "@/store/backend/EquipM/activeCarbon";
import { useAdminInfo } from "@/store/adminInfo";
import { useStandard } from "@/store/backend/LineCruiseM/standard";
import { useStandardItems } from "@/store/backend/LineCruiseM/items";

import Standard from "./standard.vue";

var timer: NodeJS.Timer;

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const formRef = ref();
const access = useAccess();
const region = useRegion();
const router = useRouter();
const route = useRoute();
const dictionary = useDictionary();
const standard = useStandard();
const items = useStandardItems();
//接受来自父组件的注入
const navTabs = inject("navTabs") as any;

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};

// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + DeviceMAccess)
      ? (navTabs as any).pageSizeMap.get(route.path + DeviceMAccess)
      : 10;
  }
  return 10;
};

//全局事件总线
const { proxy } = useCurrentInstance();
const baTable = new baTableClass(
  new baTableApi(DeviceMAccess), //this.api = api菜单管理相关
  {
    pk: "id", //设备id
    column: [
      // { type: "selection", width: "100", align: "center", operator: false },
      {
        show: filedShowOff("code"),
        label: "设备编号",
        prop: "code",
        align: "center",
        operatorPlaceholder: "精确搜索",
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          let i = standard.equipmentInfos.findIndex((val: any) => {
            return val.ecode === value;
          });
          if (i !== -1) {
            if (standard.equipmentInfos[i].state == "0") {
              //未检
              return "<p style='color:orange;'>" + value + "</p>";
            }
            return "<p style='color:#409eff;'>" + value + "</p>";
          }
          return "";
        },
      },
      {
        show: filedShowOff("cname"),
        label: "企业名称",
        prop: "cname",
        align: "center",
        operatorPlaceholder: "模糊搜索",
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          let i = standard.equipmentInfos.findIndex((val: any) => {
            return val.cname === value;
          });
          if (i !== -1) {
            if (standard.equipmentInfos[i].state == "0") {
              //未检
              return "<p style='color:orange;'>" + value + "</p>";
            }
            return "<p style='color:#409eff;'>" + value + "</p>";
          }
          return "";
        },
      },
      // {
      //   label: "巡检标准",
      //   prop: "",
      //   align: "center",
      //   render: "customRender",
      //   customRender: markRaw(Standard),
      //   operator: false,
      // },
      {
        label: "操作",
        align: "center",
        render: "buttons",
        fixed: "right",
        buttons: [
          {
            render: "tipButton",
            name: "info",
            title: "指令",
            text: "",
            type: "primary",
            icon: "iconfont icon-tianchong",
            class: "table-row-edit",
            disabledTip: false,
            display: (row: TableRow, field: TableColumn) => {
              let i = standard.equipmentInfos.findIndex(
                (value: any, index: any, arr: any) => {
                  return value.ecode === row.code;
                }
              );
              if (i !== -1) {
                return true;
              }
              return false;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
        operator: false,
      },
    ],
    filter: {
      regions: [region.regionIds] + "",
      institution: access.companyid ? access.companyid : "" + "",
      cname: route.query.cname,
      estate: route.query.estate,
      state: route.query.state,
      openState: route.query.openState,
      pageSize: pageSizeKeep(),
    },
    acceptQuery: false,
  },
  {},
  // 操作前置方法列表，返回false则取消原操作
  {
    // getList: () => {
    //   /**
    //    * 查询设备接入数据前将企业列表数据转为map格式
    //    * 1  判断所属企业列表数据是否为空
    //    */
    //   const business = useBusiness();
    //   const { companyList, companiesMap } = business;
    //   if (companyList.length === 0) {
    //     //为空就重新获取企业列表数据
    //     business.getCompanyList().then((res) => {
    //       timer = setTimeout(() => {
    //         List();
    //       }, 300);
    //     });
    //   }
    //   business.getCompanyList(); //翻页需要不触发List方法
    // },
  },
  // 操作后置方法列表，先执行表格本身的查看、删除、编辑、双击、等，再执行本处添加的后置操作
  {}
);
const List = () => {
  /**
   * 如果所属企业列表数据为空 不使用tabel类默认getList方法来获取数据
   *  使用List()方法保证在处理完企业列表之后或者所属企业列表数据为空的情况下获取数据
   */
  access
    .getAccessList({
      pageNum: 1,
      pageSize: 10,
      regions: region.regionIds + "",
      institution: access.companyid ? access.companyid : "" + "",
    })
    .then((res: any) => {
      baTable.table.data = res.rows;
      baTable.table.total = res.total;
      baTable.table.loading = false;
    });
};

const emit = defineEmits(["on-showStandardList"]);
//跳转详情页
const infoButtonClick = (id: number, row: any) => {
  console.log("id", id, "row", row);
  emit("on-showStandardList", row); //打开下级标准项列表
  let i = standard.equipmentInfos.findIndex(
    (value: any, index: any, arr: any) => {
      return value.ecode === row.code;
    }
  );
  // 巡检设备equipmentInfos数据中包含的标准id
  standard.$state.groupIds = standard.equipmentInfos[i].groupIds;
  items.$state.groupIds = standard.equipmentInfos[i].groupIds;
  //巡检设备数据索引
  standard.$state.itemsIndex = i;
  items.$state.itemsIndex = i;
};

// interface Region {
//   address: string | null;
//   addressDetail: string | null;
//   areaFlag: string | null;
//   areaId: number;
//   areaName: string | null;
//   areaNo: string | null;
//   children: Region[];
//   createBy: string | null;
//   createTime: string | null;
//   endTime: string | null;
//   params: any;
//   parentId: number;
//   searchValue: string | null;
//   startTime: string | null;
//   updateBy: string | null;
//   updateTime: string | null;
// }
//接收区域树传递过来的数据
// const filetrRegion = (row: Region, node: any) => {
//   if (node.checkedKeys.length == 0) {
//     //表示取消选择直接调用刷新表单方法
//     baTable.comSearch.form = Object.assign(baTable.comSearch.form, {
//       regions: region.regionIds + "",
//     });
//     baTable.onTableHeaderAction("refresh", {});
//   } else {
//     baTable.comSearch.form.regions = node.checkedKeys + "";
//     baTable.getList(DeviceMAccess);
//   }
// };
onBeforeRouteUpdate((to, form, next) => {
  console.log("当前路由啊,", route);
  next(false);
});

//获取菜单状态的字典
const getMenuStatus = () => {
  dictionary.getDictInfo("device_online_status").then((res: any) => {
    // state.statusDict = getDictData(res);
    dictionary.tag = getDictData(res);
    console.log("获取菜单状态的字典", dictionary.tag);
  });
};
getMenuStatus();

onMounted(() => {
  console.log("access.switch!!!!", access.switch);

  // proxy.eventBus.emit("pointer"); //el-table显示双击小手套
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  //延后查询 等待查询的前置操作
  baTable.getList(DeviceMAccess);
  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      if (!baTable.activate) return;
      if (data.name == "info") {
        infoButtonClick(
          (data.row as TableRow)[baTable.table.pk!],
          data.row as any
        );
      }
    }
  );
  proxy.eventBus.emit("clear");
});
onBeforeUnmount(() => {
  console.log("触发onBeforeUnmount");
  clearTimeout(timer);
  proxy.eventBus.emit("clear");
  proxy.eventBus.off("toMonitor");
});
// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);
</script>
<style lang="scss" scoped>
.el-main {
  padding: 0;
}
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
</style>
